import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver,EventEmitter } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import * as flatpickr from 'flatpickr';
import { zh } from "flatpickr/dist/l10n/zh.js";
import { AppPaginationComponent, PaginationModel } from "../../../../../widgets/pagination/pagination.component";
import { environment } from "../../../../../../environments/environment";
import * as _ from "lodash";
import { BatchModeService } from './batch-mode.service';
import { ViewDetailComponent } from '../../modal/view-detail/view-detail.component';
import { DataService } from 'app/services/data.service';
import { Util } from '../../../../../common/util';
@Component({
  selector: 'app-batch-mode',
  templateUrl: './batch-mode.component.html',
  styleUrls: ['./batch-mode.component.scss'],
  providers: [BatchModeService]
})
export class BatchModeComponent implements OnInit {
  // 查看明细modal
  @ViewChild("viewDetail", { read: ViewContainerRef })
  viewDetail: ViewContainerRef;
  viewDetailComponent: ComponentRef<ViewDetailComponent>;
  // lodash
  public _: any = _;
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  public isCheckedAll: any = false;
  public listData: any = [];

  //传入的菜单按钮权限数组（区别开条目录入的批次模式和条目修改的在途批次）
  public menuResource: any;

  //分页配置
  public listPageInfo = {
    currentPageNum: 1,
    pageSize: 50,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  //查询列表getBody
  public getBody: any = {
    pageIndex: 1,
    pageSize: 50,
    sOprDateStart: "",//开始时间
    sOprDateEnd: "",//结束时间
    nBatchNoStart: "",//开始批次
    nBatchNoEnd: ""//结束批次
  };
  constructor(
    public resolver: ComponentFactoryResolver,
    public batchModeService: BatchModeService,
    public dataService: DataService
  ) { }

  ngOnInit() {
    let that = this;
    this.loadlist();
    // 权限处理
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    this.menuResourceSet = [];
    that.menuResourceSet = this.menuResource
    sessionStorage.setItem('btn-NQDII', this.menuResourceSet);
    console.info(this.menuResourceSet);
    //重新定义发射事件，避免多次接收
    this.dataService.nQDIIBatchModelEmitter = new EventEmitter();
    this.dataService.nQDIIBatchModelEmitter.subscribe((value: any) => {
      if (value) {
        switch (value) {
          case 'refreshBatchList':
            this.loadlist();
            window['$']('#modal4').modal('hide');
            break;
        }
      }
    })
  }
  // 条数分页
  sizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.loadlist();
    }
  }
  // 列表分页
  pageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.loadlist(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }
  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) {
      // 更新为全选
      _.forEach(this.listData, item => {
        item.isChecked = true;
      });
    } else {
      // 更新为不全选
      _.forEach(this.listData, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.listData.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 查看明细modal
  showViewDetail() {
    // 判断组件是否已创建，如果创建先注销
    if (this.viewDetailComponent && this.viewDetailComponent.instance) {
      this.viewDetailComponent.destroy();
    }
    let checkList = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    // 动态创建组件的实例
    if (checkList.length == 1) {
      const viewDetailComponent = this.resolver.resolveComponentFactory(ViewDetailComponent);
      this.viewDetailComponent = this.viewDetail.createComponent(viewDetailComponent);
      this.viewDetailComponent.instance.viewDetailType = '1';
      this.viewDetailComponent.instance.menuResource = this.menuResource;
      this.viewDetailComponent.instance.receivedItem = checkList[0];
      window['$']('#modal4').modal('show');
    } else {
      window["swal"]("提示", "请选择一条记录！", "warning");
    }
  }
  //查询分页列表
  loadlist(pageNum?, pageSize?) {
    let that = this;
    let listData = [];
    this.isCheckedAll = false;
    this.getBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    this.getBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    this.batchModeService.list(this.getBody).subscribe(data => {
      if (data) {
        this.listData = data.list;
        console.log(data);
        this.listPageInfo.currentPageNum = data.pageNum;
        this.listPageInfo.totalPages = data.pages;
        this.listPageInfo.total = data.total;
        this.listPageInfo.startRow = data.startRow;
        this.listPageInfo.endRow = data.endRow;
      }
    })
  }
  //搜索查询
  searchQuery() {
    let that = this;
    if (Util.dateOrder(that.getBody.sOprDateStart, that.getBody.sOprDateEnd)) {
      if (that.getBody.nBatchNoEnd != '' && that.getBody.nBatchNoStart != '') {
        if (parseInt(that.getBody.nBatchNoEnd) > parseInt(that.getBody.nBatchNoStart)) {
          that.loadlist();
        } else {
          window['swal']("提示", "起始批次 须小于 结束批次", "warning");
        }
      } else {
        that.loadlist();
      }
    } else {
      window['swal']("提示", "发行日期 须早于 到期日期", "warning");
    }
  }
   // 点击表格头排序
   orderData(colName) {
    let listDataAsc = _.orderBy(this.listData, [colName], ["asc"]);
    if (JSON.stringify(this.listData) == JSON.stringify(listDataAsc)) {
      listDataAsc = _.orderBy(this.listData, [colName], ["desc"]);
    }
    this.listData = listDataAsc;
  }
}
